<template>
  <!-- Two-way Data-Binding -->
  <div class="preve-container">
    <div class="preve-content">
      <div class="preve-write" v-loading="loading">
        <div class="write-from">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-position="top"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="商品介绍标题" prop="title">
              <el-input
                class="input-write"
                v-model="ruleForm.title"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input
                class="input-write"
                v-model="ruleForm.price"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="sort">
              <el-radio-group v-model="ruleForm.sort">
                <el-radio label="时令蔬菜"></el-radio>
                <el-radio label="新鲜水果"></el-radio>
                <el-radio label="乳品饮料"></el-radio>
                <el-radio label="速食冻品"></el-radio>
                <el-radio label="粮油调味"></el-radio>
                <el-radio label="肉蛋水产"></el-radio>
                <el-radio label="休闲零食"></el-radio>
                <el-radio label="居家百货"></el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="detail-info">
              <el-form-item class="info-item" label="商品产地" prop="place">
                <el-input
                  class="input-write"
                  v-model="ruleForm.place"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item class="info-item" label="商品规格" prop="guige">
                <el-input
                  class="input-write"
                  v-model="ruleForm.guige"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <div class="info-item" id="shelf-life">
                <el-form-item class="info-item" label="保质期" prop="shelfLife">
                  <el-input
                    class="input-write"
                    v-model.number="ruleForm.shelfLife"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                  <el-select
                    v-model="ruleForm.unit"
                    placeholder="请选择保质期单位"
                  >
                    <el-option label="月" value="月"></el-option>
                    <el-option label="日" value="日"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <el-form-item class="info-item" label="储存方式" prop="howSave">
                <el-input
                  class="input-write"
                  v-model="ruleForm.howSave"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </div>

            <el-form-item
              label="商品介绍图片 (第一张图片将作为封面，最多六张)"
              class="up-img"
            >
              <div class="write-img">
                <el-upload
                  class="upload-demo"
                  name="file"
                  :action="action"
                  ref="upload1"
                  :auto-upload="false"
                  :limit="6"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :multiple="true"
                  list-type="picture-card"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过4M
                  </div>
                  <div class="tip-red" v-show="imgShow1">
                    请上传图片
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="图文介绍" class="up-img">
              <div class="write-img">
                <el-upload
                  class="upload-demo"
                  name="file"
                  :action="action"
                  ref="upload2"
                  :auto-upload="false"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload2"
                  :on-success="handleAvatarSuccess2"
                  :multiple="true"
                  list-type="picture-card"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过4M
                  </div>
                  <div class="tip-red" v-show="imgShow2">
                    请上传图片
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >立即发布</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="write-img"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { baseUrl, request } from "@/network/request.js";
export default {
  name: "vueName",
  data() {
    let patter = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
    let isNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else if (!patter.test(value)) {
        return callback(new Error("必须非负整数或至多保留两位小数"));
      } else {
        callback();
      }
    };
    return {
      content: "", //默认显示的标题，可以附带默认样式
      imgShow2: false,
      imgShow1: false,
      action: baseUrl + "/add_cart_img",
      headers: {
        "Access-Control-Allow-Origin": "*",
        sort: "1",
      },
      ruleForm: {
        title: "",
        price: "",
        sort: "",
        place: "",
        guige: "",
        shelfLife: "",
        unit: "",
        howSave: "",
      },

      rules: {
        title: [
          { required: true, message: "请输入商品标题", trigger: "blur" },
          { min: 5, max: 35, message: "长度在 5到 35 个字符", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { validator: isNumber, trigger: "blur" },
        ],
        sort: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        place: [{ required: true, message: "请选择产地", trigger: "blur" }],
        guige: [{ required: true, message: "请选择规格", trigger: "blur" }],
        shelfLife: [
          { required: true, message: "请选择保质期", trigger: "blur" },
          { type: "number", message: "必须为数字值", trigger: "blur" },
        ],
        unit: [{ required: true, message: "请选择单位", trigger: "change" }],
        howSave: [
          { required: true, message: "请选择储存方式", trigger: "blur" },
        ],
      },
      loading: false,
      IsFile: false,
      IsFile2: false,
      itemImg: [],
      tuWenImg: [],
      imgNum: 0,
      imgTuWenNum: 0,
    };
  },
  created() {
    console.log(this.action);
  },

  methods: {
    //数字保留两位小数方法
    returnFloat(value) {
      // let value =Math.floor(value)
      let s = value.toString().split(".");
      console.log(s);
      if (s.length == 1) {
        value = value.toString() + ".00";
        return value;
      }
      if (s.length > 1) {
        if (s[1].length < 2) {
          value = value.toString() + "0";
        }
        return value;
      }
    },
    te() {
      this.imgShow1 = false;
      console.log("tee");
    },
    // 图片上传限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 4; //文件大小4m
      console.log(file.uid);
      // console.log(this.$refs.upload1);
      console.log("file.ui");
      if (file.uid) {
        // this.Isimg = false;
        this.imgShow1 = false;
        this.IsFile = true; //有图片
      } else {
        this.IsFile = false;
      }
      if (!isJPG) {
        this.$message.error("上传图片是 JPG,png格式!");
        this.loading = false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 4MB!");
        this.loading = false;
      }

      return isJPG && isLt2M;
    },
    //上传图片成功，成功后发送表单
    handleAvatarSuccess(res, file, fileList) {
      console.log("图片");
      console.log(fileList);
      this.imgNum += 1;
      // console.log(this.imgNum);
      console.log(res);
      this.itemImg = [];
      for (const i in fileList) {
        if (fileList[i].response.imgName.length > 0) {
          // console.log(fileList[i].response.imgName);
          this.itemImg.push(...fileList[i].response.imgName);
        }
      }
      console.log(this.itemImg);
      // console.log(file);

      if (this.imgNum == fileList.length) {
        this.$refs.upload2.submit();
        setTimeout(() => {
          if (!this.IsFile2) {
            this.$message.error("请上传图文");
            this.loading = false;
            return false;
          }
        }, 100);
        // this.itemImg.push(res.imgName);
        // console.log(this.itemImg);
        // this.$refs.upload2.submit();
      }
      // else {
      //   this.$refs.upload2.submit();
      //   setTimeout(() => {
      //     if (!this.IsFile2) {
      //       this.$message.error("请上传图文");
      //       this.loading = false;
      //       return false;
      //     }
      //   }, 100);
      // }
    },
    // 图片上传限制
    beforeAvatarUpload2(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 4; //文件大小4m
      console.log(file.uid);
      if (file.uid) {
        // this.Isimg = false;
        this.IsFile2 = true; //有图片
      } else {
        this.IsFile2 = false;
      }
      if (!isJPG) {
        this.$message.error("上传图片是 JPG,png格式!");
        this.loading = false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 4MB!");
        this.loading = false;
      }
      return isJPG && isLt2M;
    },
    //上传图片成功，图文,图文上传后，向数据库发送
    handleAvatarSuccess2(res, file, fileList) {
      // console.log("图文");
      // console.log(res);
      this.imgTuWenNum += 1;
      // console.log(fileList);
      this.tuWenImg = [];
      for (const i in fileList) {
        // console.log(i);
        if (fileList[i].response.imgName.length > 0) {
          this.tuWenImg.push(...fileList[i].response.imgName);
        }
      }

      if (this.imgTuWenNum == fileList.length) {
        // this.tuWenImg = res.imgName;
        let sId = this.genID(6);
        if (this.ruleForm.unit == "月") {
          this.ruleForm.shelfLife = this.ruleForm.shelfLife + "个月";
        } else {
          this.ruleForm.shelfLife = this.ruleForm.shelfLife + "天";
        }

        // console.log(this.itemImg);
        // console.log(this.tuWenImg);
        request({
          method: "post",
          url: "/add_cart_item",
          data: {
            s_id: sId,
            title: this.ruleForm.title,
            price: this.returnFloat(this.ruleForm.price),
            sort: this.ruleForm.sort,
            place: this.ruleForm.place,
            guige: this.ruleForm.guige,
            shelfLife: this.ruleForm.shelfLife,
            howSave: this.ruleForm.howSave,
            itemImg: JSON.stringify(this.itemImg),
            tuWenImg: JSON.stringify(this.tuWenImg),
          },
        })
          .then((res) => {
            this.$message({
              message: "发布成功",
              type: "success",
            });
            setTimeout(() => {
              this.loading = false;
              this.$router.push("/home/cart/cart-list");
            }, 500);
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    genID(length) {
      return Number(
        Math.random()
          .toString()
          .substr(3, length) + Date.now()
      ).toString(36);
    },
    //提交表单
    submitForm(formName) {
      //数据检验
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          this.loading = true;
          console.log("1c触发");
          this.$refs.upload1.submit();
          if (this.itemImg.length > 0) {
            this.$refs.upload2.submit();
            setTimeout(() => {
              if (!this.IsFile2) {
                this.$message.error("请上传图文");
                this.loading = false;
                return false;
              } else {
              }
            }, 100);
          }
          // console.log(this.IsFile);
          setTimeout(() => {
            if (!this.IsFile) {
              this.$message.error("请上传商品图片");
              this.loading = false;
              return false;
            }
            // else {
            //   if (this.itemImg.length > 0) {
            //     this.$refs.upload2.submit();
            //     setTimeout(() => {
            //       if (!this.IsFile2) {
            //         this.$message.error("请上传图文");
            //         this.loading = false;
            //         return false;
            //       } else {
            //       }
            //     }, 100);
            //   }
            // }
          }, 100);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //预览
    handlePreview(file) {
      console.log(file + "11");
    },
    // 文章内容限制

    navTo(routerUrl) {
      console.log(routerUrl);

      this.$router.push({
        path: routerUrl,
        query: {
          // // category: getCategoryName(this.data.category),
          // categoryText: '畅销精选'
        },
      });
    },
  },
  computed: {},
  mounted() {
    // console.log("this is current quill instance object", this.editor);
  },
};
</script>

<style lang="scss">
@import "@/assets/styles/global.scss";
.preve-container {
  padding: 20px;
  .preve-content {
    padding-bottom: 100px;
    .preve-write {
      .write-from {
        width: 100%;
        // height: 100vh;
        background-color: #fff;
        padding: 20px;
        box-sizing: border-box;
        .input-write {
          width: 50%;
        }
      }

      .up-img {
        border: 1px solid #eee;
        box-sizing: border-box;
        padding: 0 10px 10px 10px;
        // position: relative;
        .tip-red {
          color: #f56c6c;
          font-size: 12px;
          position: absolute;
          bottom: -37%;
          left: 0;
        }
      }
      .detail-info {
        display: flex;
        .info-item {
          padding-left: 35px;
        }
        .input-write {
          width: 150px;
        }
        #shelf-life {
          display: flex;
        }
      }
      .info-item:nth-of-type(1) {
        padding-left: 0;
      }
    }
  }
}
</style>
